package com.fight.strive.sys.modules.auth.interceptor;

import com.fight.strive.sys.modules.auth.dto.StriveAuthInfo;
import com.fight.strive.sys.modules.auth.service.StriveAuthService;
import com.fight.strive.sys.modules.exception.exceptions.StriveInvalidTokenException;
import com.fight.strive.sys.utils.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 安全认证拦截器
 */
@Component
public class StriveAuthInterceptor implements HandlerInterceptor {

    @Resource
    private StriveAuthService striveAuthService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            // 跨域处理
            return true;
        }
        StriveAuthInfo info = null;
        String token = request.getHeader("token");
        if (ObjectUtils.notNull(token)) {
            info = striveAuthService.getAuthByToken(token);
        }
        if (ObjectUtils.notNull(info)) {
            return true;
        } else {
            // 未认证
            throw new StriveInvalidTokenException();
        }
    }

}
